package cn.zs.supply.common.core.exception;

import cn.zs.supply.common.constants.enums.ErrorCodeEnum;
import org.apache.commons.lang3.StringUtils;

public class BusiException extends RuntimeException {

    protected String code;
    protected Object[] args;

    public BusiException() {
        super();
    }

    /**
     * @param code           错误编码
     * @param args           错误消息参数，用于国际化时替换message中的变量，参考{@link org.springframework.context.MessageSource}
     * @param defaultMessage 默认消息
     * @param cause          异常原因
     */
    public BusiException(String code, Object[] args, String defaultMessage, Throwable cause) {
        super(defaultMessage, cause);
        this.code = code;
        this.args = args;
    }

    public BusiException(String code, String defaultMessage, Throwable cause) {
        this(code, null, defaultMessage, cause);
    }

    public BusiException(ErrorCodeEnum errorCodeEnum, Throwable cause) {
        super(errorCodeEnum.getMsg(), cause);
        this.code = errorCodeEnum.getCode();
    }

    public BusiException(ErrorCodeEnum errorCodeEnum, Object[] args, Throwable cause) {
        super(errorCodeEnum.getMsg(), cause);
        this.code = errorCodeEnum.getCode();
        this.args = args;
    }

    public BusiException(ErrorCodeEnum errorCodeEnum, String customMsg) {
        this(errorCodeEnum.getCode(), null, errorCodeEnum.getMsg() + ":" + customMsg, null);
    }

    public BusiException(ErrorCodeEnum errorCodeEnum) {
        this(errorCodeEnum, null, null);
    }

    public BusiException(String code, Object[] args, String defaultMessage) {
        this(code, args, defaultMessage, null);
    }

    public BusiException(String code, String defaultMessage) {
        this(code, null, defaultMessage, null);
    }

    public BusiException(String code, Object[] args, Throwable cause) {
        this(code, args, null, cause);
    }

    public BusiException(String code, Throwable cause) {
        this(code, null, null, cause);
    }

    public BusiException(String code, Object[] args) {
        this(code, args, null, null);
    }

    public BusiException(String code) {
        this(code, null, null, null);
    }

    public String getCode() {
        return code;
    }

    public boolean isErrorOf(String code) {
        return StringUtils.equals(code, this.code);
    }

    @Override
    public String getMessage() {
        return super.getMessage();
    }

    @Override
    public String getLocalizedMessage() {
        return super.getLocalizedMessage();
    }

    @Override
    public String toString() {
        String s = getClass().getName();
        String message = getLocalizedMessage();
        return (message != null) ? (s + ": " + message) : (s + ": " + code);
    }
}
